package com.it.gmall.list.listener;

import com.it.gmall.list.service.ListService;
import com.it.gmall.mq.consts.MqConst;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class ListListener {
    @Autowired
    private ListService listService;

    // 接收上架的消息
    @RabbitListener(bindings = @QueueBinding(
        exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_GOODS),
        value = @Queue(value = MqConst.QUEUE_GOODS_UPPER,durable = "true",autoDelete = "false"),
        key = {MqConst.ROUTING_GOODS_UPPER}
    ))
    public void ReceiveOnSaleMsg(long skuId, Message message, Channel channel){
        try {
            // 上架商品
            listService.onSale(skuId);
            // 手动应答
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 接收下架的消息
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_GOODS),
            value = @Queue(value = MqConst.QUEUE_GOODS_LOWER,durable = "true",autoDelete = "false"),
            key = {MqConst.ROUTING_GOODS_LOWER}
    ))
    public void ReceiveCancelSaleMsg(long skuId,Message message,Channel channel){
        try {
            // 下架商品
            listService.cancelSale(skuId);
            // 手动应答
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
